from django.forms import model_to_dict
from rest_framework import serializers

from apps.publish import models


# 话题序列化器
class TopicSerializers(serializers.ModelSerializer):

    class Meta:
        model = models.TopicModel
        fields = '__all__'

    def create(self, validated_data):
        topic = models.TopicModel(**validated_data)
        topic.save()
        return validated_data



# 发布图片序列化器
class PublishImageSerializers(serializers.Serializer):
    key = serializers.CharField()
    cos_path = serializers.CharField()



# 发布信息序列化器
class PublishModelSerializer(serializers.ModelSerializer):
    imageList = PublishImageSerializers(many=True)
    class Meta:
       model =  models.PublishModel
       exclude = ["user","favor_count","viewer_count","comment_count"]


    def create(self, validated_data):
        print(validated_data)
        # 首先过滤掉图片
        image_list = validated_data.pop("imageList")
        # 将前端传来的数据存入数据库中 并存入变量 publis_object
        publis_object = models.PublishModel.objects.create(**validated_data)

        print(f"publis_object:{publis_object}")

        # 批量存储图片到数据库中
        data_list = models.PublishImageModel.objects.bulk_create(
            [models.PublishImageModel(**info, article=publis_object) for info in image_list]
        )

        publis_object.imageList = data_list

        if publis_object.topic:
            publis_object.topic.count +=1
            publis_object.save()
        return publis_object


